#include "GBOF.h"

#include "XMLTree.h"

#include "Util.h"
#include "HBSD.h"

using namespace std;

string GBOF::xmlFromBundle(Bundle* bundle) 
{
	string xml = "<gbof_id creation_ts=\"" + bundle->creationTimestamp;
	xml += string("\" frag_length=\"") + Util::to_string(bundle->fragLength) + string("\" frag_offset=\"") + Util::to_string(bundle->fragOffset);
	if (bundle->isFragment) 
	{
		xml += "\" is_fragment=\"true\">";
	} else 
	{
		xml += "\" is_fragment=\"false\">";
	}
	xml += "<source uri=\"" + bundle->sourceURI + "\"/></gbof_id>";
	return xml;
}


string GBOF::xmlFromParms(long timestamp, int len, int offset, bool frag, string uri)
{
	string xml = "<gbof_id creation_ts=\"" + Util::to_string(timestamp);
	xml += "\" frag_length=\"" + Util::to_string(len) +
		"\" frag_offset=\"" + Util::to_string(offset);
	if (frag) 
	{
		xml += "\" is_fragment=\"true\">";
	} else 
	{
		xml += "\" is_fragment=\"false\">";
	}
	xml += "<source uri=\"" + uri + "\"/></gbof_id>";
	return xml;
}

string GBOF::keyFromBundleObject(Bundle* bundle)
{
	return makeKey(bundle->creationTimestamp, bundle->fragLength, bundle->fragOffset, bundle->isFragment, bundle->sourceURI);
}



string GBOF::keyFromXML(XMLTree* element) 
{
	try 
	{
		XMLTree * el = element->getChildElementRequired(string("source"));

		bool tmp; 

		if(element->getAttrRequired(string("is_fragment")).compare("true") == 0)
			tmp = true;
		else tmp = false;

		return makeKey(element->getAttrRequired(string("creation_ts")), element->getAttrRequired(string("frag_length")), element->getAttrRequired(string("frag_offset")), tmp, el->getAttrRequired(string("uri")));
	} 
	catch (exception &e) 
	{
		return NULL;
	}
}



string GBOF::eidFromURI(string uri) 
{
	if (uri.find_first_of("dtn://") == string::npos) 
	{
		return NULL;
	}
	int cnt = 0;
	int sz = uri.length();
	int indx = 0;
	for (indx=0; indx<sz; indx++) 
	{
		if (uri.at(indx) == '/') 
		{
			if (++cnt == 3) 
			{
				break;
			}
		}
	}
	return uri.substr(0, indx);
}



